<template>
  <c-form-dialog
    label-width="140px"
    :title="tableId ? '修改项目信息' : '新增项目信息'"
    ref="form"
    class="project-new-form"
    :table-name="formTable"
    :form-items="formItems"
    :form-data="formData"
    :before-save="handleBeforeSave"
    :table-id="tableId"
    :visible.sync="innerVisible"
    @close="handleDismiss"
    v-on="$listeners"
  >
    <span class="validate-result ml-3" slot="appendSlot">
      <i class="fa fa-check text-success"></i>
      <i class="fa fa-times text-danger"></i>
    </span>
  </c-form-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { sub, idCardValidate, licenseValidate } from '@vimi/utils-tool'

import { phoneValidator } from '@/common/plugins/validator'
import { enumDispute } from '@/bank/plugins/enum'
import { enumMainBusiness, enumParentMainBusiness } from '@/credit/plugins/enum'

import SelectAddress from '@/components/select/SelectAddress'
// import { deltaDay } from '@/common/plugins/tools/date'

const enumMainBusinessLabel = Object.keys(enumMainBusiness).map(key => ({
  value: enumMainBusiness[key],
  label: enumMainBusiness[key],
}))

const enumParentMainBusinessLabel = Object.keys(enumParentMainBusiness).map(key => ({
  value: enumParentMainBusiness[key],
  label: enumParentMainBusiness[key],
}))

export const enumCustomType = {
  // org_farm: '农户',
  org_farm: '家庭农场（农户）',
  org_large_breed: '家庭农场（种养殖大户）',
  org_cooperative: '农民专业合作社',
  org_enterprise: '农业企业',
}

export default {
  components: {},
  props: {
    visible: Boolean,
    tableId: String,
    formData: { type: Object, default: () => ({}) },
    isBackData: { type: Boolean, default: false },
    isHaveTemplate: { type: Boolean, default: false },
  },
  data() {
    const idCardValidator = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!idCardValidate(value) && !licenseValidate(value)) {
        callback(new Error('错误的身份证号，请重新输入'))
      } else {
        callback()
      }
    }
    const rateValidator = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (value > (+this.accessData.load_rate || 8.5)) {
        callback(new Error(`贷款利率最高可为：${this.accessData.load_rate || 8.5}%`))
      } else {
        callback()
      }
    }
    const dateMonth = (startDate, endDate) => {
      const newEndDate = this.$utils.dateFormat(new Date(+new Date(endDate) + 8.64e7), 'yyyy-MM-dd')
      const date1 = startDate.split('-')
      const date1Month = parseInt(date1[0]) * 12 + parseInt(date1[1])
      const date2 = newEndDate.split('-')
      const date2Month = parseInt(date2[0]) * 12 + parseInt(date2[1])
      const month = sub(date2[2], date1[2]) < 0 ? 1 : 0
      const m = Math.abs(date2Month - date1Month) - month
      return m
    }
    const dateValidator = (rule, value, callback) => {
      const startDate = this.$utils.dateFormat(this.startData, 'yyyy-MM-dd')
      const endData = this.$utils.dateFormat(this.endData, 'yyyy-MM-dd')
      const day = dateMonth(startDate, endData)
      if (value === '') {
        callback(new Error('请输入贷款期限'))
      } else if (day !== +value) {
        callback(new Error('贷款起止时间与贷款期限不匹配'))
      } else {
        callback()
      }
    }
    const businessValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!enumMainBusinessLabel.find(item => item.value === value)) {
        callback(new Error('十二大产业分类错误'))
      } else {
        callback()
      }
    }
    return {
      formTable: 'datum_one_county_industry',
      innerVisible: false,
      startData: '',
      endData: '',
      formItems: [
        {
          tag: 'input',
          itemAttrs: {
            label: '借款人/担保客户',
            rules: [{ required: true, message: '请输入借款人/担保客户', trigger: 'blur' }],
          },
          attrs: { key: 'customer_name', value: '', placeholder: '请输入借款人/担保客户' },
          appendSlot: 'appendSlot',
          listeners: {
            change: v => {
              this.$refs.form.setAttrs('corp_name', { value: v })
            },
          },
        },
        {
          tag: 'select',
          itemAttrs: {
            label: '客户类型',
            rules: { required: true, message: '请选择客户类型', trigger: 'change' },
          },
          attrs: { clearable: false, key: 'org_class', options: enumCustomType },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '行业类型',
            rules: { required: true, message: '请输入行业类型', trigger: 'change' },
          },
          attrs: { clearable: false, key: 'main_business_bank', placeholder: '请输入行业类型' },
          appendSlot: 'appendSlot',
          ifRender: () => this.isHaveTemplate && this.tableId,
        },
        {
          tag: 'select',
          itemAttrs: {
            label: '十二大产业',
            rules: [
              { required: true, message: '请选择十二大产业', trigger: 'change' },
              { validator: businessValidator, trigger: 'change' },
            ],
          },
          attrs: { clearable: false, key: 'main_business', options: enumMainBusinessLabel },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'select',
          itemAttrs: {
            label: '行业分类',
            rules: { required: true, message: '请选择行业分类', trigger: 'change' },
          },
          attrs: {
            clearable: false,
            key: 'parent_main_business',
            options: enumParentMainBusinessLabel,
          },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: { label: '年收入' },
          attrs: { key: 'sale_income', value: '' },
          tagSlots: [{ name: 'append', slot: '万元' }],
          appendSlot: 'appendSlot',
          directives: [
            {
              name: 'input-number',
              value: {
                fixed: 2,
              },
            },
          ],
        },
        {
          tag: 'input',
          itemAttrs: { label: '总资产' },
          attrs: { key: 'assets_total', value: '' },
          tagSlots: [{ name: 'append', slot: '万元' }],
          appendSlot: 'appendSlot',
          directives: [
            {
              name: 'input-number',
              value: {
                fixed: 2,
              },
            },
          ],
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '贷款金额/拟担保金额',
            rules: [{ required: true, message: '请输入贷款金额', trigger: 'blur' }],
          },
          attrs: { key: 'warranty_amount', value: '' },
          tagSlots: [{ name: 'append', slot: '万元' }],
          appendSlot: 'appendSlot',
          getAttrs: () => {
            return { disabled: !!this.tableId }
          },
          directives: [
            {
              name: 'input-number',
              value: {
                min: 0,
                fixed: 2,
                max: 1000,
              },
            },
          ],
        },
        {
          tag: 'date',
          itemAttrs: {
            label: '放款日/拟担保起始日',
            rules: [{ required: true, message: '请选择放款日', trigger: 'change' }],
          },
          attrs: { key: 'load_date', value: '', placeholder: '请选择日期' },
          appendSlot: 'appendSlot',
          listeners: {
            change: v => {
              this.startData = v
              this.$refs.form.validateField('warranty_period')
            },
          },
        },
        {
          tag: 'date',
          itemAttrs: {
            label: '到期日',
            rules: [{ required: true, message: '到期日', trigger: 'change' }],
          },
          appendSlot: 'appendSlot',
          attrs: { key: 'load_end_date', value: '', placeholder: '请选择日期' },
          listeners: {
            change: v => {
              this.endData = v
              this.$refs.form.validateField('warranty_period')
            },
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '贷款期限',
            rules: [{ required: true, validator: dateValidator, trigger: 'change' }],
          },
          attrs: { key: 'warranty_period', value: '', placeholder: '请输入贷款期限' },
          tagSlots: [{ name: 'append', slot: '月' }],
          appendSlot: 'appendSlot',
          directives: [
            {
              name: 'input-number',
              value: {
                min: 0,
                fixed: 0,
                max: 200,
              },
            },
          ],
        },
        {
          tag: 'number',
          step: 0.01,
          itemAttrs: {
            label: '贷款利率',
            rules: [
              { validator: rateValidator, trigger: 'blur' },
              { required: true, message: '请输入贷款利率', trigger: 'blur' },
            ],
          },
          attrs: { key: 'load_rate', value: '', placeholder: '请输入贷款利率' },
          tagSlots: [{ name: 'append', slot: '%' }],
          appendSlot: 'appendSlot',
          directives: [
            {
              name: 'input-number',
              value: {
                min: 0,
                fixed: 2,
                max: 8.5,
              },
            },
          ],
        },
        {
          tag: 'input',
          itemAttrs: { label: '担保方式' },
          attrs: { key: 'warranty_method', value: '', placeholder: '请输入担保方式' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'radio-group',
          itemAttrs: { label: '是否购买农业保险' },
          attrs: { clearable: false, key: 'is_buy_insurance', value: '0', options: enumDispute },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '贷款用途',
            rules: [{ required: true, message: '请输入贷款用途', trigger: 'blur' }],
          },
          attrs: { key: 'funds_use_dir', value: '', placeholder: '请输入贷款用途' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'radio-group',
          itemAttrs: { label: '是否为扶贫项目' },
          attrs: { clearable: false, key: 'is_poverty_project', value: '0', options: enumDispute },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: { label: '征信逾期次数' },
          attrs: { key: 'overdue_count', value: '', placeholder: '征信逾期次数' },
          tagSlots: [{ name: 'append', slot: '次' }],
          appendSlot: 'appendSlot',
          directives: [
            {
              name: 'input-number',
              value: {
                min: 0,
                fixed: 0,
              },
            },
          ],
        },
        {
          tag: 'input',
          itemAttrs: { label: '征信逾期合计金额' },
          attrs: { key: 'overdue_funds', value: '', placeholder: '征信逾期金额' },
          tagSlots: [{ name: 'append', slot: '万元' }],
          appendSlot: 'appendSlot',
          directives: [
            {
              name: 'input-number',
              value: {
                min: 0,
                fixed: 2,
              },
            },
          ],
        },
        {
          tag: 'input',
          itemAttrs: { label: '联系人' },
          attrs: { key: 'corp_name', value: '', placeholder: '联系人' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '联系电话',
            rules: [
              { required: true, message: '请输入手机号码', trigger: 'blur' },
              { validator: phoneValidator, message: '请输入正确的手机号码', trigger: 'blur' },
            ],
          },
          attrs: { key: 'corp_phone', value: '', placeholder: '联系电话' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '客户身份证号码/统一社会信用代码',
            rules: [
              { required: true, message: '请输入身份证号码/统一社会信用代码', trigger: 'blur' },
              {
                validator: idCardValidator,
                message: '请输入正确的身份证号码/统一社会信用代码',
                trigger: 'blur',
              },
            ],
          },
          attrs: { key: 'lender_idcard', value: '', placeholder: '请输入信息' },
          appendSlot: 'appendSlot',
        },
        {
          tag: SelectAddress,
          itemAttrs: {
            label: '客户住址/经营地址',
            rules: { required: true, message: '请选择经营地址', trigger: 'change' },
          },
          attrs: { key: 'address_code', value: '', class: 'form-control-ml', aotuTop: true },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: { label: '详细地址' },
          attrs: { key: 'address_detail', value: '', placeholder: '请输入地址' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '保证合同号',
          },
          attrs: { key: 'gua_contract', value: '', placeholder: '请输入保证合同号' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: { label: '备注' },
          attrs: { key: 'remark', value: '', placeholder: '请输入备注' },
        },
      ],
    }
  },
  computed: {
    ...mapGetters(['clientId', 'org', 'accessData']),
  },
  watch: {
    visible(val) {
      this.innerVisible = val
      if (val) {
        if (this.tableId) {
          this.startData = this.formData.load_date
          this.endData = this.formData.load_end_date
          this.$nextTick(() => {
            const cfrom = this.$refs.form
            const form = cfrom.$refs.cForm.$refs.form
            form.validate(() => {})
          })
        } else {
          this.$refs.form.setAttrs('gua_contract', { value: this.accessData.gua_contract })
        }
      }
    },
  },
  created() {
    this.$store.dispatch('getAccessData')
  },
  mounted() {},
  methods: {
    handleBeforeSave(model) {
      if (this.tableId) {
        model.import_batch_no = this.formData.import_batch_no
      }
      model.submit_type = 2
      model.bank_id = this.clientId
      model.bank_name = this.org.orgName
      model.bank_code = this.org.orgCode
      model.org_class_name = enumCustomType[model.org_class]
      // model.service_id = '42b33648-5691-43fa-8b04-16bf9901260f'

      if (this.isBackData) {
        this.$emit('back', model)
        return
      }
      return model
    },
    handleDismiss() {
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped>
.project-new-form {
  .validate-result {
    display: none;
  }
  .is-success {
    .validate-result {
      display: inline-block;
      .fa-times {
        display: none;
      }
    }
  }
  .is-error {
    .validate-result {
      display: inline-block;
      .fa-check {
        display: none;
      }
    }
  }
}
</style>
